package com.cloudOffice.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudOffice.constant.GlobalConstant;
import com.cloudOffice.constant.HttpConstant;
import com.cloudOffice.constant.SystemConstant;
import com.cloudOffice.execption.SystemException;
import com.cloudOffice.mapper.*;
import com.cloudOffice.model.system.SysRole;
import com.cloudOffice.model.system.SysUser;
import com.cloudOffice.model.system.SysUserRole;
import com.cloudOffice.service.SysMenuService;
import com.cloudOffice.service.SysUserService;
import com.cloudOffice.utils.JwtUtils;
import com.cloudOffice.utils.Md5Util;
import com.cloudOffice.vo.system.LoginVo;
import com.cloudOffice.vo.system.RouterVo;
import com.cloudOffice.vo.system.SysUserQueryVo;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: cloud-office
 * @className: SysRoleServiceImpl
 * @description: SysRoleService
 * @data: 2024/2/4 15:51
 * @author: ihu
 * @version: 1.0
 **/

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
	
	@Resource
	private SysMenuService sysMenuService;
	@Resource
	private SysUserRoleMapper sysUserRoleMapper;
	@Resource
	private SysRoleMapper sysRoleMapper;
	@Resource
	private SysRoleMenuMapper sysRoleMenuMapper;
	@Resource
	private SysMenuMapper sysMenuMapper;
	@Resource
	private RedisTemplate<String, String> redisTemplate;
	
	/**
	 * 登录
	 */
	@Override
	public Map<String, Object> login(LoginVo loginVo) {
		if (StringUtils.isEmpty(loginVo.getUsername()) || StringUtils.isEmpty(loginVo.getPassword())) {
			throw new SystemException(HttpConstant.CODE_201, SystemConstant.LOGIN_USERNAME_PASSWORD_EMPTY);
		}
		SysUser sysUser = getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, loginVo.getUsername()));
		if (sysUser == null) {
			throw new SystemException(HttpConstant.CODE_201, SystemConstant.LOGIN_USERNAME_EMPTY);
		}
		if (sysUser.getStatus().equals(GlobalConstant.INTEGER_ZERO)) {
			throw new SystemException(HttpConstant.CODE_201, SystemConstant.LOGIN_USERNAME_DISABLE);
		}
		if (!Md5Util.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
			throw new SystemException(HttpConstant.CODE_201, SystemConstant.LOGIN_PASSWORD_ERROR);
		}
		return againGetToken(sysUser.getId(), sysUser.getUsername());
	}
	
	@Override
	public IPage<SysUser> index(Long page, Long limit, SysUserQueryVo sysUserQueryVo) {
		//创建page对象
		Page<SysUser> pageParam = new Page<>(page, limit);
		//封装条件
		LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
		wrapper.like(!StringUtils.isEmpty(sysUserQueryVo.getKeyword()), SysUser::getUsername,
				sysUserQueryVo.getKeyword()).ge(!StringUtils.isEmpty(sysUserQueryVo.getCreateTimeBegin()),
				SysUser::getCreateTime, sysUserQueryVo.getCreateTimeBegin()).le(!StringUtils.isEmpty(sysUserQueryVo.getCreateTimeEnd()), SysUser::getCreateTime, sysUserQueryVo.getCreateTimeEnd());
		//实现条件分页查询
		return page(pageParam, wrapper);
	}
	
	/**
	 * 更新状态
	 */
	@Override
	public void updateStatus(Long id, Integer status) {
		SysUser sysUser = getById(id);
		if (status.equals(GlobalConstant.INTEGER_ONE)) {
			sysUser.setStatus(GlobalConstant.INTEGER_ZERO);
		}
		sysUser.setStatus(status);
		updateById(sysUser);
	}
	
	@Override
	public Map<String, Object> getUserInfo(String username) {
		Map<String, Object> map = new HashMap<>();
		SysUser sysUser = getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
		//根据用户id获取菜单权限值
		List<RouterVo> routerVoList = sysMenuService.findUserMenuList(sysUser.getId());
		//根据用户id获取用户按钮权限
		List<String> permsList = sysMenuService.findUserPermsList(sysUser.getId());
		
		String headUrl = sysUser.getHeadUrl() != null ? sysUser.getHeadUrl() : "https://wpimg.wallstcn" +
				".com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
		
		List<SysRole> sysRoles =
				sysUserRoleMapper.selectList(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, sysUser.getId())).stream().map(e -> sysRoleMapper.selectById(e.getRoleId())).collect(Collectors.toList());
		
		map.put("name", sysUser.getName());
		map.put("avatar", headUrl);
		map.put("roles", sysRoles);
		map.put("buttons", permsList);
		map.put("routers", routerVoList);
		return map;
	}
	
	@Override
	public Map<String, Object> againGetToken(Object id, String username) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", id);
		map.put("username", username);
		String token = JwtUtils.create(map);
		redisTemplate.opsForValue().set(id + username, token, JwtUtils.TOKEN_EXPIRATION_TIME, TimeUnit.SECONDS);
		Map<String, Object> hashMap = new HashMap<>();
		hashMap.put("token", token);
		hashMap.put("endTime", LocalDateTime.now());
		return hashMap;
	}
}
